package top.whysu.edevice.controller.dtu;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.whysu.edevice.dto.generate.ResponseDTO;
import top.whysu.edevice.utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * DTU相关
 */
@Controller
@RequestMapping("/dtu")
public class DtuController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DtuController.class);

    /**
     * 接收传感器数据
     */
    @PostMapping(value = "/reportData")
    @ResponseBody
    public void reportData(@RequestBody String jsonBodyJsonStr) {
        LOGGER.info("接收到传感器/船舶数据：{}", jsonBodyJsonStr);
    }

    /**
     * 接收消息
     */
    @PostMapping("/reportDataJson")
    @ResponseBody
    public ResponseDTO reportDataJson(HttpServletRequest request) {
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            LOGGER.info("接收：{}", responseStrBuilder);
        } catch (Exception e) {
            LOGGER.error("失败", e);
        }
        return ResponseUtil.getSuccessResponse();
    }
}